﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HighPerformanceLog;
using HighPerformanceLog.V2;
using Microsoft.Win32;
using Microsoft.WindowsAPICodePack.Dialogs;
using Newbeecoder.UI;
using Ookii.Dialogs.Wpf;
using ProcessBarDemo.UpdateFramework;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using test.Views;
using test.Views.SettingControl;
using XMLConfig;



namespace test.ViewModels
{
    public partial class MainViewModel : ObservableObject
    {
        [ObservableProperty]
        private string infoMessage = "东东电竞全民争霸最新公告 …… 07/03";
        //进度条的值
        [ObservableProperty]
        private double progressValue = 0;
        //进度条的圆圈的值
        [ObservableProperty]
        private double circleValue;
        [ObservableProperty]
        private bool isComponentVisible = true;
        [ObservableProperty]
        private bool isLoading = false;
     
        //退出选择项
        [ObservableProperty]
        private bool isOption1Selected;

        [ObservableProperty]
        private bool isOption2Selected;
        //退出界面使用的
        [ObservableProperty]
        private bool quiTeyes = true;
        [ObservableProperty]
        private bool quiTeno = false;
        //是否开机自启动
        [ObservableProperty]
        private bool autotoStart;
        //是否选择自动更新
        [ObservableProperty]
        private bool autoUpdate;
        public Action? CloseWindowAction { get; set; }
        private UpdateManager updater = new UpdateManager();


        //下载地址
        [ObservableProperty]
        private string baseDirectory;
        //设置中的隐藏或者关闭选择按钮
        [ObservableProperty]
        private bool closeWindow;

        [ObservableProperty]
        private bool behindWindow;
        //关闭界面中是否不再提示的按钮
        [ObservableProperty]
        private bool donotShow;
        //检测软件是否需要更新
        string localIni = "config\\system.ini";
        string remoteIni = "https://dongdong-1328553122.cos.ap-nanjing.myqcloud.com/dongdong-client/system.ini";
        string updatePath = Path.GetFullPath(Path.Combine("config", "update_files.xml"));
        //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------











































        //下载路径修改设置

        [RelayCommand]
        private void ChooseFile()
        {

            string selectedDir;
            bool success = DialogUtil.GetDir("请选择一个文件夹", out selectedDir, @"C:\Users\Public");

            if (success)
            {
                // 在这里你可以处理用户选择的路径
                BaseDirectory = selectedDir;
                ConfigPathgetorset(2);

            }
        }




































        //读取config保存路径与xml-------------------------------------------------------------------------------------------
        //获取下载路径
        private ConfigManager configManager;

        public MainViewModel()
        {
            Configmanager();  // 确保在对象创建时初始化 configManager
            ConfigPathgetorset(1);
            AutoStart.SetAutoStart(AutotoStart, "dongdong");
            UpdateChecker();
            



        }

        private void Configmanager()
        {



            string binDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            string configFilePath = Path.Combine(binDirectory, "config", "config.xml");

            configManager = new ConfigManager(configFilePath);

        }
        public const int Initialize = 1;
        public const int Save_date = 3;
        public const int path_set = 2;
        private void ConfigPathgetorset(int select)
        {



            // 初始化 baseDirectory
            switch (select)
            {
                case Initialize:
                    BaseDirectory = configManager.GetValue("savePath") ;
                    string autoStartValue = configManager.GetValue("AutoStart");

                    AutotoStart = bool.TryParse(autoStartValue, out bool i) ? i : AutotoStart;

                    string autoupdateValue = configManager.GetValue("AutoUpdate");

                    
                    
                        AutoUpdate = bool.TryParse(autoupdateValue, out bool j)?j:AutotoStart;
                   
                    //接下来的两个是设置里面的选择的初始化

                    string behindwindow = configManager.GetValue("BehindWindows");

                        IsOption1Selected = bool.TryParse(behindwindow, out bool a)?a:IsOption1Selected;

                    

                    
                    string closewindows = configManager.GetValue("CloseWindows");

                   
                        IsOption2Selected = bool.TryParse(closewindows, out bool b)?b:IsOption2Selected;

                    

                    //接下来是选择是否不再提示和关闭界面的初始化
                    
                    string dontshow = configManager.GetValue("DonotShow");

                  
                        DonotShow = bool.TryParse(dontshow, out bool c)?c:DonotShow;

                    

                    break;
                case path_set:
                    configManager.SetValue("savePath", BaseDirectory);


                    break;
                case Save_date:

                    configManager.SetValue("AutoStart", AutotoStart.ToString());
                    configManager.SetValue("AutoUpdate", AutoUpdate.ToString());
                    configManager.SetValue("BehindWindows", IsOption1Selected.ToString());
                    configManager.SetValue("CloseWindows", IsOption2Selected.ToString());
                    
                    configManager.Save();
                    ConfigPathgetorset(1);
                    AutoStart.SetAutoStart(AutotoStart, "dongdong");


                    break;
            }

        }
        private setting setting;
        [RelayCommand]
        private void SavePath()
        {
            ConfigPathgetorset(3);
            CloseSettingWindow();
        }

        private void CloseSettingWindow()
        {
            // 调用关闭窗口的方法
            setting?.Close();
        }


        [RelayCommand]
        private void Confirm_donotshow()
        {
            if (DonotShow)
            {
                configManager.SetValue("DonotShow", DonotShow.ToString());

                configManager.Save();
            }
            ConfirmSelection();
        }













        //退出和隐藏到托盘的选择--------------------------------------------------------------------------------------------------------------------------------------————————————————————————————————————————————————————————————————————————
        [RelayCommand]
        private void ConfirmSelection()
        {
            QuiTeyes = true;
            QuiTeno = false;

            if (IsOption1Selected)
            {
                // 执行选项 1 的操作


                foreach (Window window in System.Windows.Application.Current.Windows)
                {
                    window.Hide();
                }
                if (DonotShow)
                {
                    configManager.SetValue("DonotShow", DonotShow.ToString());

                    configManager.Save();
                }
            }
            else if (IsOption2Selected)
            {
                // 执行选项 2 的操作

                QuiTeyes = false;
                QuiTeno = true;
                

            }
            else
            {
                // 如果没有选择任何选项
                System.Windows.Forms.MessageBox.Show("未选择任何选项！" + IsOption2Selected + IsOption1Selected);
            }
        }









        //关闭整个程序
        [RelayCommand]
        private void Confirmquite()
        {
            System.Environment.Exit(0);

        }
        [RelayCommand]
        private void Cancelquite()
        {
            CloseWindowAction?.Invoke();
        }
















        [RelayCommand]

        //开始和更新——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
        private async Task Update()
        {
            IsComponentVisible = false;
            string binDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string xmlPath = Path.Combine(binDirectory, "config", "update_files.xml");

            updater.LoadUpdateConfig(xmlPath, BaseDirectory);
            Task updateTask1 = Task.Run(() => StartDownload());

            await updateTask1;
            // 例如：Process.Start("game.exe");
        }
        [RelayCommand]
        private void StartGame()
        {
            System.Windows.Forms.MessageBox.Show("正在启动游戏...", "启动提示");
        }



        //设置窗口开启
        [RelayCommand]
        private void Openset()
        {
            // 创建并显示第二个窗口
            setting = new setting();
            setting.DataContext = this;




            setting.Show(); // 显示第二个窗口

        }






        [RelayCommand]
        private void VisitWebsite()
        {
            Process.Start(new ProcessStartInfo("https://dongdongdianjing.com/#/") { UseShellExecute = true });
        }

        [RelayCommand]
        private void ReportIssue()
        {
            Process.Start(new ProcessStartInfo("https://dongdongdianjing.com/#/") { UseShellExecute = true });
        }


        private Closedown closedown;
          
        public void initialclose()
        {
             closedown=new Closedown(this);
            closedown.DataContext = this;
        }
        [RelayCommand]

        //开关按钮
       
        private void Close()
        {
            
        
            closedown.Show();
           

            if (DonotShow)
            {
                ConfirmSelection();
            }
        }

        [RelayCommand]
        private void Minimize()
        {


            // 执行最小化
            System.Windows.Application.Current.MainWindow.WindowState = WindowState.Minimized;

           


        }
        [RelayCommand]
        private async Task StartDownload()
        {
            IsLoading = true;  // 显示进度条
            ProgressValue = 0; // 初始化进度条值
            await SimulateFileDownload(); // 启动进度条更新
        }
        public async Task SimulateFileDownload()
        {

            Task updateTask = Task.Run(() => updater.StartDownloadAll());
            while (ProgressValue < 100)
            {
                await Task.Delay(200); // 模拟下载进度
                ProgressValue = Math.Round(DownloadService.process, 2); // 更新进度条
                CircleValue = ProgressValue * 12.8;

            }
            if (ProgressValue == 100)
            {
                IsLoading = false; // 隐藏控件
                IsComponentVisible = true;

            }
            await updateTask;
        }
        //——————————————————————————————————————————————————————————————————————————






        //检测软件是不是需要更新

        [RelayCommand]
        public void UpdateChecker()
        {
            var checker = new UpdateChecker(localIni, remoteIni, updatePath, intervalMs: 60000);
            string xmlPath = Path.Combine(BaseDirectory, "dongdongdianjing.exe");

            if (checker.CheckAndDownloadIfMissing(xmlPath))
            {
                checker.VersionChecked += (s, e) =>
                {
                    if (e.HasUpdate)
                    {
                        //此时说明版本需要更新
                        //isUpdate=true;
                        //处理更新逻辑
                        if (AutoUpdate == true)
                        {
                            Update();
                        }
                        else
                        {
                            IsComponentVisible = true;
                            checker.Stop();
                        }

                    }
                    else
                    {
                        
                        checker.Stop();
                    }
                };
            }
            else
            {
                IsComponentVisible = true;
            }
            //bool isUpdate = False;//标记是否需要更新



            checker.Start();
        }






























    }
}